﻿using ELTE.SEM.Common;
using ELTE.SEM.Common.Enums;
using ELTE.SEM.Data.Managers;
using ELTE.SEM.Data.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace ELTE.NPRG.WEB.Controllers
{
    public class AccountController : ControllerBase
    {
        UserManager Manager { get; set; }

        public AccountController()
            : base()
        {
            this.Manager = new UserManager(this.DataEntities);
        }

        public ActionResult Index()
        {

            if (User.Identity.IsAuthenticated)
            {
                //redirect to the main page
                return RedirectToAction("Index", "Home");
            }
            else
            {
                //redirect to the login page
                return RedirectToAction("Login");
            }
        }

        public ActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                Session["LoginResult"] = Manager.Authenticate(model);
                if ((bool)Session["LoginResult"])
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, true);
                }
            }
            else
            {
                Session["LoginResult"] = false;
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult SUReg()
        {
            //ha a felhasználó belépett, szerepkör-vizsgálat után a kért oldal visszaadása
            //ha nincs bejelentkezve, vagy a felhasználói szint nem megfelelő -> redirektálás a főoldalra
            if (User.Identity.IsAuthenticated)
            {
                UserRoleLevel usersLevel = Manager.GetUsersRole(User.Identity.Name);
                if (usersLevel == UserRoleLevel.Admin || usersLevel == UserRoleLevel.FullAdmin || usersLevel == UserRoleLevel.Operator)
                {
                    return View();
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult SUReg(RegisterViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                UserRoleLevel usersLevel = Manager.GetUsersRole(User.Identity.Name);
                if (usersLevel == UserRoleLevel.Admin || usersLevel == UserRoleLevel.FullAdmin || usersLevel == UserRoleLevel.Operator)
                {
                    if (ModelState.IsValid)
                    {
                        ViewBag.Result = Manager.Register(model);
                    }
                    return View();
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }


        public ActionResult UserRoleManagement()
        {
            if (User.Identity.IsAuthenticated)
            {
                UserRoleLevel usersLevel = Manager.GetUsersRole(User.Identity.Name);
                if (usersLevel == UserRoleLevel.Admin || usersLevel == UserRoleLevel.FullAdmin || usersLevel == UserRoleLevel.Operator)
                {
                    List<UserViewModel> usersList = Manager.GetUsersWithRole(0, ConfigHelper.ValueInt("UserRoleAmountToDisplay"));
                    return View(usersList);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
            
        }

        [HttpPost]
        public JsonResult UserRoleManagement(int pageNumber)
        {
            List<UserViewModel> usersList = Manager.GetUsersWithRole(pageNumber, ConfigHelper.ValueInt("UserRoleAmountToDisplay"));
            return Json(usersList, JsonRequestBehavior.AllowGet);
        }

        public ActionResult UserFoldersManagement(int uid)
        {
            if (User.Identity.IsAuthenticated)
            {
                UserRoleLevel usersLevel = Manager.GetUsersRole(User.Identity.Name);
                if (usersLevel == UserRoleLevel.Admin || usersLevel == UserRoleLevel.FullAdmin || usersLevel == UserRoleLevel.Operator)
                {
                    UserFoldersViewModel model = Manager.GetUserFolderAccess(uid, false);
                    return View(model);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
            
        }

        [HttpPost]
        public ActionResult UserFoldersManagement(UserFoldersViewModel model, FormCollection collection)
        {
            for (int i = 0; i < model.FolderAccess.Count; i++)
            {
                if (model.FolderAccess[i] != null)
                {
                    model.FolderAccess[i].HasAccess = collection[String.Format("FolderAccess[{0}].HasAccess", i)].StartsWith("on");
                }
            }
            if (Manager.SetUserFolderAccess(model))
            {
                ViewBag.UserFolderManagementSuccessMessage = "Sikeres mentés";
            }
            else
            {
                ViewBag.UserFolderManagementFailedMessage = "Mentés sikertelen";
            }
            UserFoldersViewModel viewModel = Manager.GetUserFolderAccess(model.UserId, false);
            return View(viewModel);
        }

        [HttpPost]
        public JsonResult ChangeUserName(string fromUserName, string toUserName)
        {
            bool changeResult = false;
            if (User.Identity.IsAuthenticated)
            {
                changeResult = Manager.ChangeName(fromUserName, toUserName);
                if (changeResult && fromUserName == User.Identity.Name)
                {
                    FormsAuthentication.SignOut();
                    FormsAuthentication.SetAuthCookie(toUserName, true);
                }
            }
            return Json(changeResult, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ChangeUserRole(string userName, int newRoleId)
        {
            return Json(Manager.ChangeRole(userName, newRoleId), JsonRequestBehavior.AllowGet);
        }

    }
}
